package main

import "fmt"

/**
 * 使用滑动窗口计数
 */
func main() {
	nums := []int{2, 5, 3, 7, 9, 6, 4, 2, 1, 8, 3, 6}
	winLen := 5

	sums := windowSum(nums, winLen)
	fmt.Println(sums)

}

func windowSum(nums []int, winLen int) []int {
	sums := make([]int, len(nums)-winLen+1)

	lastSum := nums[0]
	for i := 0; i+winLen <= len(nums); i++ {
		if lastSum == nums[0] { //窗口为空
			lastSum = sum(nums[0:winLen])
		} else { //滑动窗口记录前一窗口的结果，只对窗口两端的值进行操作
			lastSum = lastSum - nums[i-1] + nums[i-1+winLen]
		}

		sums[i] = lastSum
	}

	return sums
}

func sum(nums []int) int {
	sum := 0
	for _, v := range nums {
		sum += v
	}

	return sum
}
